﻿using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;

namespace MvcSample.Filters
{
    public class GlobalModelValidationFilter
        : IActionFilter
    {
        public void OnActionExecuted(ActionExecutedContext context)
        {
            
        }

        public void OnActionExecuting(ActionExecutingContext context)
        {
            if (context.ModelState.IsValid)
            {
                return;
            }
            var validations = context.ModelState.Values.Where(v => v.ValidationState == Microsoft.AspNetCore.Mvc.ModelBinding.ModelValidationState.Invalid);
            if (validations != null && validations.Any())
            {
                var errorMsgs = validations.SelectMany(v => v.Errors).Select(e => e.ErrorMessage);
                context.Result = new OkObjectResult(string.Join(",", errorMsgs));
            }
        }
    }
}
